//
//  JMLivenessVC.m
//  NewiOSProject
//
//  Created by MAC on 2023/9/26.
//  Copyright © 2023 范智渊. All rights reserved.
//
#import <AVFoundation/AVFoundation.h>

#import "JMSlicenseVC.h"
#import "JMOriginCardNumVC.h"
#import "JMChangeMyBankController.h"
//@interface JMLivenessVC ()

@interface JMSlicenseVC ()
{
    BOOL livenessCheckResult;
}
@property(nonatomic, strong)UIButton *backBtn;//中间捕获画面视图
@property(nonatomic, strong)UIButton * cameraBtn;//中间捕获画面视图
@property(nonatomic, strong)UILabel *titleLab;//中间捕获画面视图
@property(nonatomic, strong)UILabel *tipsLab;//中间捕获画面视图
@property(nonatomic, strong)UIImageView *captureView;//中间捕获画面视图
@property(nonatomic, strong)UIImageView * botView;//中间捕获画面视图
@property (nonatomic,strong)UIImageView *loadingImgV;

//活体检测id
@property (nonatomic, strong)NSString * livenessId;
//活体检测返回图片
@property (nonatomic, strong)NSString * photoName;

//AAILiveness 所需license
@property (nonatomic, strong)NSString * licenseString;

//MARK: - 静默活体相关
@property (nonatomic, strong) UIView *slicenseView;
@property (nonatomic, strong) AVCaptureSession *captureSession;
@property (nonatomic, strong) AVCaptureVideoPreviewLayer *previewLayer;
@property (nonatomic, strong) AVCaptureStillImageOutput *stillImageOutput;
@property (nonatomic, strong) UIView *slicenseFailureView;

@end

@implementation JMSlicenseVC

- (void)viewDidLoad {
    [super viewDidLoad];
    [self.view addSubview:self.slicenseView];
    [self configCapture];
}

-(void)configCapture{
    // 初始化捕获会话
    self.captureSession = [[AVCaptureSession alloc] init];

    // 查找前置摄像头设备
    AVCaptureDevice *frontCamera = nil;
    NSArray *devices = [AVCaptureDevice devicesWithMediaType:AVMediaTypeVideo];
    for (AVCaptureDevice *device in devices) {
        if (device.position == AVCaptureDevicePositionFront) {
            frontCamera = device;
            break;
        }
    }
    // 添加截图输出
    self.stillImageOutput = [[AVCaptureStillImageOutput alloc] init];
    [self.captureSession addOutput:self.stillImageOutput];
    
    // 设置前置摄像头输入设备
    NSError *error = nil;
    AVCaptureDeviceInput *input = [AVCaptureDeviceInput deviceInputWithDevice:frontCamera error:&error];
    if (input) {
        [self.captureSession addInput:input];
    } else {
        NSLog(@"Error setting up front camera input: %@", error);
    }
    
    // 创建视频预览层并将其添加到视图上
    self.previewLayer = [AVCaptureVideoPreviewLayer layerWithSession:self.captureSession];
    self.previewLayer.videoGravity = AVLayerVideoGravityResizeAspectFill;
    self.previewLayer.frame = self.view.bounds;
    [self.slicenseView.layer insertSublayer:self.previewLayer atIndex:0];
    
    // 启动捕获会话
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_BACKGROUND, 0), ^{
        [self.captureSession startRunning];
    });
}

//MARK: -
-(void)slicenseViewBackBtnClick{
    [self.navigationController popViewControllerAnimated:YES];
}
-(void)goNewCardVC{
    [self stopAnimating];
    JMChangeMyBankController *vc = JMChangeMyBankController.new;
    [self pushVCDestoryCurrent:vc];
//    [self.navigationController pushViewController:vc animated:YES];
}
- (void)captureStillImage {
    AVCaptureConnection *stillImageConnection = [self.stillImageOutput connectionWithMediaType:AVMediaTypeVideo];
    
    if (stillImageConnection) {
        [self.stillImageOutput captureStillImageAsynchronouslyFromConnection:stillImageConnection completionHandler:^(CMSampleBufferRef imageDataSampleBuffer, NSError *error) {
            if (!error) {
                NSData *imageData = [AVCaptureStillImageOutput jpegStillImageNSDataRepresentation:imageDataSampleBuffer];
                UIImage *image = [UIImage imageWithData:imageData];
                // 在这里处理截图，例如显示到UIImageView或保存到相册
                // image就是截取到的静态图像
                
                [self uploadSlicenseLivenessImg:image];
            } else {
                NSLog(@"Error capturing still image: %@", error);
            }
        }];
    }
}
-(void)startAnimating{
    // 启动捕获会话
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_BACKGROUND, 0), ^{
        [self.captureSession stopRunning];
    });
    [self.cameraBtn setImage:nil forState:(UIControlStateNormal)];
    [self.cameraBtn addSubview:self.loadingImgV];
    delayOperation(0, ^{
        CALayer *loadingLayer = [CALayer layer];
        loadingLayer.bounds = CGRectMake(0, 0, self.loadingImgV.width, self.loadingImgV.height);
        loadingLayer.position = CGPointMake(self.loadingImgV.width / 2, self.loadingImgV.height / 2);
        loadingLayer.contents = (id)[UIImage imageNamed:@"loading-white"].CGImage; // 使用你自己的加载图片
        [self.loadingImgV.layer addSublayer:loadingLayer];
        
        CABasicAnimation *rotationAnimation = [CABasicAnimation animationWithKeyPath:@"transform.rotation"];
        rotationAnimation.fromValue = [NSNumber numberWithFloat:0.0];
        rotationAnimation.toValue = [NSNumber numberWithFloat:M_PI * 2.0];
        rotationAnimation.duration = 2.0; // 旋转一圈所需的时间
        rotationAnimation.repeatCount = HUGE_VALF; // 无限循环
        [loadingLayer addAnimation:rotationAnimation forKey:@"rotationAnimation"];        
    });
}

//静默活体 拍照后上传图片
-(void)uploadSlicenseLivenessImg:(UIImage*)img{

     NSString *path = @"/api/common/oss-upload-live?livenChannelEnum=SILENCE_LIVENESS";
     NSURL *url = [NSURL URLWithString: BasePostRequestUrl(path)];
    [JMBaseRequest.sharedInstance requestUploadBasePost:path params:nil pictures:img success:^(NSDictionary * _Nonnull data) {
        if (data) {
            delayOperation(0, ^{
                [self.loadingImgV removeFromSuperview];
                [self.navigationController popViewControllerAnimated:YES];
                [self configLivenessResult:data[@"livenessId"]];
                NSMutableDictionary *dict = [NSMutableDictionary dictionaryWithDictionary:data];
                dict[@"originImage"] = img;
                [JMCommonMethod uploadStatistics:@"VerifyFacial" actionType:@"Liveness_Success" parameters:nil];
                self.verifyResultBlock(dict);
            });
        }
    } fail:^(NSString * _Nonnull errorMsg) {
        [JMCommonMethod uploadStatistics:@"VerifyFacial" actionType:@"Liveness_Failure" parameters:@{@"errorMsg":errorMsg?errorMsg:@""}];

        dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_BACKGROUND, 0), ^{
            [self.captureSession startRunning];
        });
    }];
}
//4.检测结果预处理
-(void)configLivenessResult:(NSString *)livenessId{
    [[JMBaseRequest sharedInstance]  requestBasePost:BasePostRequestUrl(@"/api/auth/pre-liveness") params:@{@"livenessId":livenessId} success:^(NSDictionary * _Nullable dataDic, NSArray * _Nullable dataArray) {
        livenessCheckResult = YES;
        if (self.type==2) {
            [self checkLivenessResult:livenessId];
        }
    } fail:^(NSString * _Nonnull errorMsg) {
        livenessCheckResult = NO;
    }];
}
-(void)checkLivenessResult:(NSString *)livenessId{
    
    [[JMBaseRequest sharedInstance]  requestBasePost:BasePostRequestUrl(@"/api/auth/check-modify-bankcard-live") params:@{@"livenessId":livenessId,@"livenessImg":self.photoName,@"livenChannelEnum":@"SILENCE_LIVENESS"} success:^(NSDictionary * _Nullable dataDic, NSArray * _Nullable dataArray) {
        livenessCheckResult = YES;
        
        [self goNewCardVC];
        

    } fail:^(NSString * _Nonnull errorMsg) {
        livenessCheckResult = NO;
    }];
}
// 压缩图片到指定大小（以KB为单位）
- (NSData *)compressImage:(UIImage *)image toMaxSize:(NSUInteger)maxSizeInKB {
    CGFloat compressionQuality = 1.0;
    NSData *compressedImageData = UIImageJPEGRepresentation(image, compressionQuality);
    
    while ([compressedImageData length] > maxSizeInKB * 1024 && compressionQuality > 0.0) {
        compressionQuality -= 0.1;
        compressedImageData = UIImageJPEGRepresentation(image, compressionQuality);
    }
    return compressedImageData;
}

-(UIView *)slicenseFailureView{
    if(!_slicenseFailureView){
        _slicenseFailureView = [[UIView alloc]initWithFrame:(CGRectMake(0, 0, kAppW(), kAppH()))];
        UIView *contV = [[UIView alloc]initWithFrame:(CGRectMake(0, 0, kAppW()-50, 350))];
        
        contV.cornerRadius = 8;
        contV.backgroundColor = WhiteColor();
        [_slicenseFailureView addSubview:contV];
        
        
        UIButton *closeBtn = [JMControl createButtonWithFrame:(CGRectMake(contV.width-10-24, 18, 24, 24)) ImageName:@"auth_close" Target:self Action:@selector(failureViewDismiss) font:nil Title:nil];
        [contV addSubview:closeBtn];

        
        UIImageView *topImgV = [[UIImageView alloc]initWithFrame:(CGRectMake(0, 36, 46, 46))];
        topImgV.centerX = contV.width/2;
        topImgV.image = ImageNamed(@"auth_failure");
        [contV addSubview:topImgV];
        
        UILabel *titleLab = [JMControl createLabelWithFrame:(CGRectMake(0, topImgV.bottom+25, contV.width, FontH(14))) Font:Font(14) Text:@"Reconocimiento facial fallado" color:Hex_Str_COLOR(@"#FF3F33")];
        [contV addSubview:titleLab];
        titleLab.textAlignment = 1;
        
        UILabel *contentlab = [JMControl createLabelWithFrame:(CGRectMake(22, titleLab.bottom+25, contV.width-50, FontH(14))) Font:Font(14) Text:@"Comprueba tu enlace de Internet.Toma una nueva fotografía que cumpla con los siguientes requisitos." color:Hex_Str_COLOR(@"#0F1511")];
        [contV addSubview:contentlab];
        contentlab.height = CalculateLabelHeightWithLab(contentlab);
        contentlab.top = titleLab.bottom+25;
        
        UILabel *tipsLab = [JMControl createLabelWithFrame:(CGRectMake(22, contentlab.bottom+25, contV.width-50, FontH(14))) Font:Font(14) Text:@"Consejos:\n1. Toma una foto de frente.\n2. Dispara en un entorno libre de distracciones.\n3. No te cubras la cara.\n4. Sostén tu teléfono verticalmente y firmemente." color:Hex_Str_COLOR(@"#B7B8B7")];
        [contV addSubview:tipsLab];
        tipsLab.height = CalculateLabelHeightWithLab(tipsLab);
        tipsLab.top = contentlab.bottom+25;
        @weakify(self)
        [_slicenseFailureView tapAction:^(UIView *sender) {
            @strongify(self);
            [self failureViewDismiss];
        }];
        contV.height = tipsLab.bottom+50;
        contV.center = CGPointMake(kAppW()/2, kAppH()/2);
    }
    return _slicenseFailureView;
}
-(void)showFailureView{
//    [self slicenseViewBackBtnClick];
    delayOperation(0, ^{
        [[UIApplication sharedApplication].keyWindow addSubview: self.slicenseFailureView];
    });
}
-(void)failureViewDismiss{
    [self.slicenseFailureView removeFromSuperview];
    self.slicenseFailureView  = nil;
}
-(UIView *)slicenseView{
    if (!_slicenseView) {
        _slicenseView = [[UIView alloc]initWithFrame:self.view.bounds];
        
        _captureView = [[UIImageView alloc]initWithFrame:(CGRectMake(0, 0, kAppW(), kAppH()))];
        _captureView.image = [self getImage];
        [_slicenseView addSubview:_captureView];
        
        UIButton *backBtn = [JMControl createButtonWithFrame:(CGRectMake(41, 55, 18, 18)) ImageName:@"auth_back" Target:self Action:@selector(slicenseViewBackBtnClick) font:nil Title:nil];
        [_slicenseView addSubview:backBtn];
        
        UILabel *titleLab = [JMControl createLabelWithFrame:(CGRectMake(0, 54, kAppW(), 25)) Font:Font(20) Text:@"Foto en vivo" color:WhiteColor() textAlignment:1 numberOfLine:0];
        [_slicenseView addSubview:titleLab];
        titleLab.centerY = backBtn.centerY;
        
        
        UIImageView *faceImg = [[UIImageView alloc]initWithFrame:(CGRectMake(47,NAVIGATION_BAR_HEIGHT()+ 195, kAppW()-94, kAppW()-94))];
        [_slicenseView addSubview:faceImg];
        faceImg.layer.borderColor = mainSchemeColor().CGColor;
        faceImg.layer.borderWidth = 5;
        faceImg.layer.cornerRadius = kAppW()/2-94/2;
        
        
       
        
        _tipsLab = [JMControl createLabelWithFrame:(CGRectMake(24, titleLab.bottom+8, kAppW()-48, 45)) Font:Font(13) Text:@"Pon tu cara en el marco y toma una foto" color:HexAlpha_Str_COLOR(@"#ffffff", 1) textAlignment:1 numberOfLine:0];
        [_slicenseView addSubview:_tipsLab];
        
        _botView = [[UIImageView alloc]initWithFrame:(CGRectMake(0, kAppH()-169, kAppW(), 169))];
        _botView.backgroundColor = WhiteColor();
        _botView.userInteractionEnabled = YES;
        [_botView setRoundedCorners:(UIRectCornerTopLeft | UIRectCornerTopRight) radii:30];
        [_slicenseView addSubview:_botView];
        
        
        self.backBtn = [JMControl createButtonWithFrame:(CGRectMake(20, kSafeAreaTopHeight(), 40, 40)) ImageName:@"back_white" Target:self Action:@selector(slicenseViewBackBtnClick) font:nil Title:nil];
        [_slicenseView addSubview:self.backBtn];
        
      
        _cameraBtn = [JMControl createButtonWithFrame:(CGRectMake(0, 52, 64, 64)) ImageName:@"auth_slicense_camera" Target:self Action:@selector(captureStillImage) font:nil Title:nil];
        _cameraBtn.backgroundColor = Hex_Str_COLOR(@"#C8FF52");
        _cameraBtn.cornerRadius = 34;
        [_botView addSubview:_cameraBtn];
        _cameraBtn.centerX = kAppW()/2;
        
        
      
    }
    return _slicenseView;
}
- (UIImage *)getImage{
    UIGraphicsBeginImageContextWithOptions([UIScreen mainScreen].bounds.size, NO, 1.0);
    CGContextRef con = UIGraphicsGetCurrentContext();
    CGContextSetFillColorWithColor(con, HexAlpha_Str_COLOR(@"#000000", 0.8).CGColor);//背景色
    CGContextFillRect(con, [UIScreen mainScreen].bounds);
    CGContextAddEllipseInRect(con, CGRectMake(47, NAVIGATION_BAR_HEIGHT()+195, kAppW()-94, kAppW()-94));
    CGContextSetBlendMode(con, kCGBlendModeClear);
    CGContextFillPath(con);
    UIImage *ima = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return ima;
}
-(UIImageView *)loadingImgV{
    if(!_loadingImgV){
        _loadingImgV = [[UIImageView alloc]initWithFrame:(CGRectMake(0, 0, 32, 32))];
        _loadingImgV.contentMode = UIViewContentModeScaleAspectFill;
        _loadingImgV.centerX = self.cameraBtn.width/2;
        _loadingImgV.centerY = self.cameraBtn.width/2;
    }
    return _loadingImgV;
}

@end
